/**
 * Prompt优化工具
 */

export interface PromptLayers {
  template?: string;
  system?: string;
  smart?: string;
  frontend?: string;
  user?: string;
}

/**
 * 优化多层Prompt，去重合并
 */
export function optimizePrompts(layers: PromptLayers): string {
  // 1. 提取各层内容
  const segments = parsePromptLayers(layers);
  
  // 2. 去重
  const deduplicated = deduplicateSegments(segments);
  
  // 3. 合并
  return mergeSegments(deduplicated);
}

function parsePromptLayers(layers: PromptLayers) {
  const segments: Array<{
    type: 'role' | 'task' | 'context' | 'requirement';
    content: string;
    priority: number;
  }> = [];

  // 解析各层
  if (layers.template) {
    segments.push({ type: 'role', content: layers.template, priority: 5 });
  }
  
  if (layers.system) {
    // 提取角色
    const roleMatch = layers.system.match(/你是.*?(?=\n|$)/);
    if (roleMatch) {
      segments.push({ type: 'role', content: roleMatch[0], priority: 4 });
    }
    
    // 提取上下文
    const contextMatch = layers.system.match(/当前热点信息：[\s\S]*?(?=\n\n|$)/);
    if (contextMatch) {
      segments.push({ type: 'context', content: contextMatch[0], priority: 3 });
    }
  }
  
  if (layers.smart) {
    // 提取任务
    const taskMatch = layers.smart.match(/针对.*?撰写.*?(?=\n|$)/);
    if (taskMatch) {
      segments.push({ type: 'task', content: taskMatch[0], priority: 4 });
    }
    
    // 提取要求
    const requirements = layers.smart.match(/\d+\.\s*[^.\n]+/g);
    if (requirements) {
      segments.push({ 
        type: 'requirement', 
        content: requirements.join('\n'), 
        priority: 2 
      });
    }
  }
  
  if (layers.frontend) {
    const requirements = layers.frontend.match(/\d+\.\s*[^.\n]+/g);
    if (requirements) {
      segments.push({ 
        type: 'requirement', 
        content: requirements.join('\n'), 
        priority: 1 
      });
    }
  }
  
  if (layers.user) {
    segments.push({ type: 'requirement', content: layers.user, priority: 5 });
  }

  return segments;
}

function deduplicateSegments(segments: any[]) {
  const byType: { [key: string]: any[] } = {};
  
  // 按类型分组
  segments.forEach(seg => {
    if (!byType[seg.type]) byType[seg.type] = [];
    byType[seg.type].push(seg);
  });
  
  const result = [];
  
  // 每个类型选择最高优先级的
  Object.values(byType).forEach(typeSegs => {
    typeSegs.sort((a, b) => b.priority - a.priority);
    
    if (typeSegs[0].type === 'requirement') {
      // 要求类型需要合并去重
      const allReqs = typeSegs.flatMap(seg => 
        seg.content.match(/\d+\.\s*([^.\n]+)/g) || [seg.content]
      );
      const uniqueReqs = [...new Set(allReqs.map(req => 
        req.replace(/^\d+\.\s*/, '').trim()
      ))];
      
      result.push({
        type: 'requirement',
        content: uniqueReqs.map((req, i) => `${i+1}. ${req}`).join('\n')
      });
    } else {
      result.push(typeSegs[0]);
    }
  });
  
  return result;
}

function mergeSegments(segments: any[]): string {
  const parts = [];
  
  // 按固定顺序组织
  const role = segments.find(s => s.type === 'role');
  const task = segments.find(s => s.type === 'task');
  const context = segments.find(s => s.type === 'context');
  const requirement = segments.find(s => s.type === 'requirement');
  
  if (role) parts.push(role.content);
  if (task) parts.push(`任务：${task.content}`);
  if (context) parts.push(`上下文：\n${context.content}`);
  if (requirement) parts.push(`创作要求：\n${requirement.content}`);
  
  return parts.join('\n\n');
}
